﻿using Nop.Core.Data;
using Nop.Core.Domain.Stores;
using Nop.Core.Infrastructure;
using Nop.Services.Stores;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Services.Media
{

    public interface IContentResolver
    {
        IList<SelectListItem> GetRelatedContentList(int selectedContentId = 0);
        string Name { get; }
    }

    public class ContentResolver
    {
        private Dictionary<string, IContentResolver> _registeredContentResolver = new Dictionary<string, IContentResolver>();
        private ITypeFinder _typeFinder;

        public ContentResolver(ITypeFinder typeFinder)
        {
            _typeFinder = typeFinder;
        }

        protected virtual void RegisterContentResolvers()
        {
            if (_registeredContentResolver.Count > 0)
            {
                // Registered
                return;
            }

            var crs = _typeFinder.FindClassesOfType<IContentResolver>()
                .Select(x => Activator.CreateInstance(x) as IContentResolver);

            foreach (var cr in crs)
            {
                if (null != cr)
                {
                    _registeredContentResolver.Add(cr.Name, cr);
                }
            }
        }

        public IList<string> GetAllRelatedContentCategoryNames()
        {
            RegisterContentResolvers();
            return _registeredContentResolver.Keys.OrderBy(cr => cr).ToList();
        }

        public IList<SelectListItem> GetRelatedContantSelectList(string categoryName, int selectedContentId)
        {
            RegisterContentResolvers();

            if (categoryName == null || !_registeredContentResolver.ContainsKey(categoryName))
            {
                return null;
            }

            return _registeredContentResolver[categoryName].GetRelatedContentList(selectedContentId);
        }
    }

    public class StoreContentResolver : IContentResolver
    {
        private IStoreService _storeService = null;

        public IList<SelectListItem> GetRelatedContentList(int selectedContentId = 0)
        {
            if (_storeService == null)
            {
                _storeService = EngineContext.Current.Resolve<IStoreService>();
            }

            return _storeService.GetAllStores(true, false)
                .Select(s => new SelectListItem()
                        {
                            Text = s.Name,
                            Value = s.Id.ToString(),
                            Selected = selectedContentId != 0 ? s.Id == selectedContentId : false
                        })
                .ToList();
        }

        public string Name
        {
            get { return "Store"; }
        }
    }
}
